<template>
    <div class="front-padding" v-drag v-loading="loading[0]" element-loading-text="拼命加载中..." element-loading-spinner="el-icon-loading" element-loading-background="#fff">
        <div class="tree-left bg-white">
            <div class="tit">部门列表</div>
            <div class="tree bj bg-white">
                <el-scrollbar style="height: 100%;">
                    <el-tree :data="treedata" ref="tree" :props="defaultProps" :expand-on-click-node="false" :accordion="false" node-key="id" :default-expanded-keys="dfExpKeys" :default-expand-all="true" @node-click="handleNodeClick" :highlight-current="true"></el-tree>
                </el-scrollbar>
            </div>
        </div>
        <div class="tree-right bg-white">
            <div class="widgets bg-white">
                <el-input class="search__input" v-model="searchText" placeholder="输入搜索内容" @keyup.enter.native="searchBtn"></el-input>
                <el-button type="primary" @click="searchBtn">查询</el-button>
                <div class="btn-group right">
                    <el-button type="info" @click="refrense">刷新</el-button>
                    <el-button type="danger" v-if="multipleSelection.length <= 0" disabled>禁用</el-button>
                    <el-button type="danger" v-else @click="useordisuse(0,'禁用')">禁用</el-button>
                    <el-button type="success" v-if="multipleSelection.length <= 0" disabled>启用</el-button>
                    <el-button type="success" v-else @click="useordisuse(1,'启用')">启用</el-button>
                    <el-button type="primary" v-if="multipleSelection.length <= 0" disabled>复位</el-button>
                    <el-button type="primary" v-else @click="reset">复位</el-button>
                    <el-button type="primary" v-if="multipleSelection.length <= 0" disabled>授权</el-button>
                    <el-button type="primary" v-else @click="authorization">授权</el-button>
                    <el-button type="primary" v-if="multipleSelection.length <= 0" disabled>单据</el-button>
                    <el-button type="primary" v-else @click="documents">单据</el-button>
                    <el-button type="primary" v-if="multipleSelection.length <= 0" disabled>报表</el-button>
                    <el-button type="primary" v-else>报表</el-button>
                    <el-button-group class="btn-other">
                        <el-button title="导出" @click="exportExcel">
                            <img src="../../../assets/images/export.png" alt="">
                        </el-button>                      
                        <el-button title="打印">
                            <img src="../../../assets/images/print.png" alt="">
                        </el-button>
                        <el-button title="帮助">
                            <img src="../../../assets/images/help.png" alt="">
                        </el-button>
                    </el-button-group>
                </div>
            </div>
            <!-- 表格数据 -->
            <div class="table top-bottom bj">
                <el-scrollbar style="height: 100%;">
                    <el-table :data="result" border @selection-change="handleSelectionChange">
                        <el-table-column type="selection" align="center"></el-table-column>
                        <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
                        <el-table-column property="userName" label="用户名" align="center"></el-table-column>
                        <el-table-column property="name" label="姓名" align="center"></el-table-column>
                        <el-table-column property="deptName" label="部门" align="center"></el-table-column>
                        <el-table-column property="positionAux" label="职务" align="center"></el-table-column>
                        <el-table-column property="locks" label="状态" align="center">
                            <template slot-scope="scope">
                                <span style="color: green;" v-if="scope.row.locks == 1">已启用</span>
                                <span style="color: red;" v-else>已禁用</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="150" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="updateRow(scope.row.id)">修改</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-scrollbar>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            treedata: this.$store.state.userManagementStore.treeData,
            tableData: this.$store.state.userManagementStore.tableData,
            tables: this.$store.state.userManagementStore.tables,           //查询
            multipleSelection:[],                   //选中行
            defaultProps: {
                children: 'subDepartment',
                label: 'name'
            },
            searchText: '',                         //搜索内容
            selectRowId: [],                        //表格选中当前行的id
            userId: [],                             //表格选中当前行的userid
            userName: [],                           //表格选中当前行的username
            name: [],                               //表格选中当前行的name
            rightMenu: {
                isShowIconMove: false,              //是否显示上移、下移、置顶、置底 弹窗
                rightKeyRow: {},                    //右键点击存储的行
                rightKeyRowIndex: '',               //右键点击表格行的索引
            },
            boolean: true,
            dfExpKeys: [],
            loading: this.$store.state.userManagementStore.loading
        }
    },
    watch:{
        treedata() {
			this.$nextTick(() => {
				let expandNodeId = this.$store.state.userManagementStore.expandNodeId;
				this.dfExpKeys = [expandNodeId];
				this.$refs.tree.setCurrentKey(expandNodeId);
			});
        },
    },
    computed: {
		systemId() {
			return this.$store.state.systemId;
        },
        result() {
            const search = this.searchText;
            if(search) {
                let $util = this.$util;
                return this.tables.filter(item => {
                    return $util.keys(item).some(key => {
                        return String(item[key]).toLowerCase().indexOf(search) > -1;
                    })
                });
            }
            return this.tableData;
        }
	},
    methods: {
        handleSelectionChange(val) {                //点击表格选中触发
            this.multipleSelection = val;
            this.selectRowId = [];
            this.userId = [];
            this.userName = [];
            this.name = [];
            for(var i = 0; i < this.multipleSelection.length; i++) {
                this.selectRowId.push(this.multipleSelection[i]['id']);
                this.userId.push(this.multipleSelection[i]['userId']);
                this.userName.push(this.multipleSelection[i]['userName']);
                this.name.push(this.multipleSelection[i]['name']);
            }
            this.$store.commit('userManagementStore/updateSelectRowId', this.selectRowId);
            this.$store.commit('userManagementStore/updateUserId', this.userId);
            this.$store.commit('userManagementStore/updateUserName', this.userName);
            this.$store.commit('userManagementStore/updateName', this.name);
        },
        handleNodeClick(row) {                      //点击左侧树形结构触发该方法
            if(this.searchText) this.searchText = '';
            this.$store.commit('userManagementStore/updateExpandNodeId', row['id']);
            this.$store.dispatch('userManagementStore/getEmployeeDataByDepartmentId', row['id']);
        },
        reset() {                                   //复位
            if(this.multipleSelection.length > 0) {
                if(this.multipleSelection.length < 2){
                    this.$confirm('确定复位用户<'+ this.userName +'>的登录密码吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        var type = {
                            headers: {
                                'Content-type': 'application/json;charset=UTF-8'
                            }
                        }
                        this.$http.post(this.$url + 'userManage/updatePassword', JSON.stringify(this.userId), type).then(res => {
                            if(res.data.code == 20001) {
                                this.$message({message: this.userName+'用户的登录密码改为123456', type: 'success', duration: 2000});
                            } else {
                                this.$message.error(this.data.msg);
                            }
                        }).catch(err => {
                            this.$message.error(err);
                        });
                    })
                } else {
                    this.$message({message: '请选择单个用户进行复位', type: 'warning'});
                }
            } else {
                this.$message({message: '请选择你要复位的用户', type: 'warning'});
            }
        },
        resetTwo(row) {                             //单个复位
            this.$confirm('确定复位用户<'+ row['userName'] +'>的登录密码吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var type = {
                    headers: {
                        'Content-type': 'application/json;charset=UTF-8'
                    }
                }
                this.$http.post(this.$url + 'userManage/updatePassword', JSON.stringify([row['userId']]), type).then(res => {
                    if(res.data.code == 20001) {
                        this.$message({message: row['userName'] +'用户的登录密码改为123456', type: 'success', duration: 2000});
                    } else {
                        this.$message.error(this.data.msg);
                    }
                }).catch(err => {
                    this.$message.error(err);
                });
            })
        },
        authorization() {                           //授权
            if(this.multipleSelection.length > 0) {
                if(this.multipleSelection.length < 2){
                    this.$util.openLayerIframe({title: '授权', zIndex: 13, width: '55%', height: '85%', url: this.$domain + '/#/userManagement/Authorization'});
                } else {
                    this.$message({message: '只能选择单个用户进行授权', type: 'warning'});
                }
            } else {
                this.$message({message: '选择你要授权的用户', type: 'warning'});
            }
        },
        authorizationOne(row) {                     //单个授权
            this.$util.openLayerIframe({title: '授权', zIndex: 13, width: '55%', height: '85%', url: this.$domain + '/#/userManagement/Authorization'});
        },
        documents() {                               //单据
            if(this.multipleSelection.length > 0) {
                if(this.multipleSelection.length < 2){
                    this.$util.openLayerIframe({title: '审批单据授权设置', zIndex: 13, width: '65%', height: '85%', url: this.$domain + '/#/userManagement/Documents'});
                } else {
                    this.$message({message: '只能选择单个用户进行授权', type: 'warning'});
                }
            } else {
                this.$message({message: '选择你要授权的用户', type: 'warning'});
            }
        },
        useordisuse(locks, msg){                    //禁用和启用
            if(this.multipleSelection.length > 0) {
                var type = {
                    headers: {
                        'Content-type': 'application/json;charset=UTF-8'
                    }
                }
                if(locks == 0) {       //禁用
                    for(var i = 0; i < this.multipleSelection.length; i++) {
                        if(this.multipleSelection[i]['locks'] == locks) {
                            this.$alert('禁用失败，其中包含已禁用选项，重新选择！', '禁用提示', {
                                confirmButtonText: '确定'
                            });
                            return false;
                        }
                    }
                } else if(locks == 1) {
                    for(var i = 0; i < this.multipleSelection.length; i++) {
                        if(this.multipleSelection[i]['locks'] == locks) {
                            this.$alert('启动失败，其中包含已启动选项，重新选择！', '启动提示', {
                                confirmButtonText: '确定'
                            });
                            return false;
                        }
                    }
                }
                this.$http.post(this.$url + 'userManage/locksUser?locks=' + locks, JSON.stringify(this.userId), type).then(res => {
                   if(res.data.code == 20001) {
                        this.$message({message: msg + '成功', type: 'success', duration: 2000});
                        setTimeout(() => {
                            let expandNodeId = this.$store.state.userManagementStore.expandNodeId;
                            this.$store.dispatch('userManagementStore/getEmployeeDataByDepartmentId', expandNodeId);			//刷新数据
                            this.$store.dispatch('userManagementStore/getSearch');
                        }, 1000);
                    } else {
                        this.$message.error(this.data.msg);
                    }
                }).catch(err => {
                    this.$message.error(err);
                });
            } else {
                this.$message({message: '选择你要'+ msg +'的数据', type: 'warning'});
            }
        },
        disabedBtnOneList(locks, msg, row) {        //禁用单条
            var type = {
                headers: {
                    'Content-type': 'application/json;charset=UTF-8'
                }
            }
            if(locks == 0) {
                if(row['locks'] == locks) {
                    this.$message.error('禁用失败！当前数据已是禁用状态');
                    return false;
                }
            }
            if(locks == 1) {
                if(row['locks'] == locks) {
                    this.$message.error('启用失败！当前数据已是启用状态');
                    return false;
                }
            }
            this.$http.post(this.$url + 'userManage/locksUser?locks=' + locks, JSON.stringify([row['userId']]), type).then(res => {
                if(res.data.code == 20001) {
                    this.$message({message: msg + '成功', type: 'success', duration: 2000});
                    setTimeout(() => {
                    	let expandNodeId = this.$store.state.userManagementStore.expandNodeId;
                        this.$store.dispatch('userManagementStore/getEmployeeDataByDepartmentId', expandNodeId);			//刷新数据
                        this.$store.dispatch('userManagementStore/getSearch');
                    }, 1000);
                } else {
                    this.$message.error(this.data.msg);
                }
            }).catch(err => {
                this.$message.error(err);
            });
        },
        refrense(){                                 //刷新
            const loading = this.$loading({
                lock: true,
                text: '数据刷新中...',
                spinner: 'el-icon-loading',
                background: '#fff'
            });
            setTimeout(() => {
                loading.close();
            }, 1000);
        },
        exportExcel(){                              //导出
            if(this.multipleSelection.length > 0) {
                var idSting = this.selectRowId.join(',');           //将[1,2,3]格式转为 "1,2,3"
                this.$http.get(this.$url + 'userManage/exportUser',{params: { idList: idSting }}).then(res => {
                    this.$message({message: '导出成功', type: 'success'});
                    window.location.href = this.$url + 'userManage/exportUser?idList=' + idSting;          //导出时触发
                }).catch(err => {
                    this.$message.error(err);
                })
            } else {
                this.$message({message: '选择你要导出的数据', type: 'warning', duration: 2000});
            }
        },
        updateRow($id){                             //修改
            this.$store.commit('userManagementStore/updateRowId', $id);
            this.$util.openLayerIframe({title: '用户管理-修改', zIndex: 13,  width: '500px', height: '370px', url: this.$domain + '/#/userManagement/updateUserManagement'});
        },
        searchBtn(){                                //搜索
            // if(this.searchText) {
            //     let newArr = [],
            //         data = this.$store.state.userManagementStore.searchData,
            //         searchText = this.searchText;
            //     let reg = new RegExp(this.searchText, "g");
            //     data.forEach(item => {
            //         if((reg.test(item['name']) || reg.test(item['userName']) || reg.test(item['positionAux']) || reg.test(item['deptName']) || item['toNamePinyin'] && reg.test(item['toNamePinyin'])) || (item['toSimplePinyin'] && reg.test(item['toSimplePinyin'])) || (item['toPosionPinyin'] && reg.test(item['toPosionPinyin'])) || (item['toSimpleUsernamePinyin'] && reg.test(item['toSimpleUsernamePinyin'])) || (item['toUserNamePinyin'] && reg.test(item['toUserNamePinyin'])) || (item['toSimplePosionPinyin'] && reg.test(item['toSimplePosionPinyin']))) {
            //             newArr.push(item);
            //         }
            //     });
            //     this.tableData = newArr;
            // }
        }
    },
    mounted() {
        this.$store.commit('userManagementStore/updateExpandNodeId');          //初始化展开节点
        this.$store.dispatch('userManagementStore/getTreeData');
        this.$store.dispatch('userManagementStore/getSearch');
    }
}
</script>